package com.sg.service.base.framework.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.base.framework.req.BatchQueryAppReq;
import com.sg.dto.base.framework.req.QueryAppDetailReq;
import com.sg.dto.base.framework.req.QueryAppForPushMemoryDetailReq;
import com.sg.dto.base.framework.req.QueryAppListReq;
import com.sg.entity.UnionApp;
import com.sg.service.base.framework.MUnionAppService;
import com.wicket.okrframework.common.dto.FieldInfo;
import com.wicket.okrframework.common.exception.BizException;
import com.wicket.okrframework.dal.mapper.mbg.UnionAppMapper;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：
 * @version 1.0
 * @since 2022/1/19 15:39
 */
@Service
public class MUnionAppServiceImpl
        extends ServiceImpl<UnionAppMapper, UnionApp>
        implements MUnionAppService {

    @Autowired
    UnionAppMapper unionAppMapper;

    /**
     * 1-2-06查询联盟应用详情[168]
     * gen by moon at 10/23/2022, 2:25:43 PM
     */
    @Trace(operationName = "1-2-06查询联盟应用详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UnionApp queryAppDetail(QueryAppDetailReq reqDto) {

        try {
            reqDto.setIsValid("FALSE");
            QueryWrapper<UnionApp> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<UnionApp> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                UnionApp retData = retList.get(0);
                retData.setAppLogo(CommonFunctionHelper.getFilePath(retData.getAppLogo()));//otherModel: ALL_PATH
                retData.setAboutLogo(CommonFunctionHelper.getFilePath(retData.getAboutLogo()));//otherModel: ALL_PATH
                retData.setAppBanner(CommonFunctionHelper.getFilePath(retData.getAppBanner()));//otherModel: ALL_PATH
                retData.setAppBigBanner(CommonFunctionHelper.getFilePath(retData.getAppBigBanner()));//otherModel: ALL_PATH

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-2-06批量查询联盟应用列表[1548]
     * gen by moon at 10/23/2022, 2:25:44 PM
     */
    @Trace(operationName = "1-2-06批量查询联盟应用列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<UnionApp> batchQueryApp(BatchQueryAppReq reqDto) {

        try {
            QueryWrapper<UnionApp> queryWrapper = new QueryWrapper<>();

            if (reqDto.getUnionAppList() == null || reqDto.getUnionAppList().isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in("app_id", reqDto.getUnionAppList());
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(UnionApp.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(UnionApp.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(UnionApp.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            // TODO: 2024/5/30  
            List<UnionApp> retList = super.list(queryWrapper);
            for (UnionApp one : retList) {
                one.setAppBigBanner(CommonFunctionHelper.getFilePath(one.getAppBigBanner()));
                one.setAppLogo(CommonFunctionHelper.getFilePath(one.getAppLogo()));
                one.setAboutLogo(CommonFunctionHelper.getFilePath(one.getAboutLogo()));
                one.setAppBanner(CommonFunctionHelper.getFilePath(one.getAppBanner()));
            }
            return retList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-2-06查询联盟应用列表[68]
     * gen by moon at 10/23/2022, 2:25:42 PM
     */
    @Trace(operationName = "1-2-06查询联盟应用列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<UnionApp> queryAppList(QueryAppListReq reqDto) {

        try {
            QueryWrapper<UnionApp> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(UnionApp.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(UnionApp.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(UnionApp.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            queryWrapper.orderByDesc("operate_time");
            return ((List<UnionApp>) super.list(queryWrapper)).stream().map(item -> {
                item.setAppLogo(CommonFunctionHelper.getFilePath(item.getAppLogo()));//otherModel: ALL_PATH
                return item;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-2-06删除联盟应用[67]
     * gen by moon at 10/23/2022, 2:25:42 PM
     */
    @Trace(operationName = "1-2-06删除联盟应用")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteApp(String appId) {

        return super.removeById(appId);
    }

    /**
     * 1-2-06修改联盟应用[66]
     * gen by moon at 10/23/2022, 2:25:41 PM
     */
    @Trace(operationName = "1-2-06修改联盟应用")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateApp(UnionApp unionApp) {
        // TODO: 2024/1/19
//     if(!StringUtils.isEmpty(unionApp.getAppLogo())){
//         unionApp.setAppLogo(CommonFunctionHelper.replaceFilePath(unionApp.getAppLogo()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAboutLogo())){
//         unionApp.setAboutLogo(CommonFunctionHelper.replaceFilePath(unionApp.getAboutLogo()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAppBanner())){
//         unionApp.setAppBanner(CommonFunctionHelper.replaceFilePath(unionApp.getAppBanner()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAppBigBanner())){
//         unionApp.setAppBigBanner(CommonFunctionHelper.replaceFilePath(unionApp.getAppBigBanner()));
//     }
        unionApp.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            unionApp.setReleaseInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//RELEASED_CURRENT_INDUCTIONID
        }
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("ARCHIVING")) {
            unionApp.setArchiveInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//ARCHIVE_CURRENT_INDUCTIONID
        }
        unionApp.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            unionApp.setReleaseTime(CommonFunctionHelper.getCurrentTime());//RELEASE_SYSTEM_CURRENT_TIME
        }
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("ARCHIVING")) {
            unionApp.setArchiveTime(CommonFunctionHelper.getCurrentTime());//HISTORICAL_ARCHIVING
        }
        return super.updateById(unionApp);
    }

    /**
     * 1-2-06新增联盟应用[65]
     * gen by moon at 5/17/2023, 3:44:29 AM
     */
    @Trace(operationName = "1-2-06新增联盟应用")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addApp(UnionApp unionApp) {
        // TODO: 2024/1/19
//     if(!StringUtils.isEmpty(unionApp.getAppLogo())){
//         unionApp.setAppLogo(CommonFunctionHelper.replaceFilePath(unionApp.getAppLogo()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAboutLogo())){
//         unionApp.setAboutLogo(CommonFunctionHelper.replaceFilePath(unionApp.getAboutLogo()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAppBanner())){
//         unionApp.setAppBanner(CommonFunctionHelper.replaceFilePath(unionApp.getAppBanner()));
//     }
//     if(!StringUtils.isEmpty(unionApp.getAppBigBanner())){
//         unionApp.setAppBigBanner(CommonFunctionHelper.replaceFilePath(unionApp.getAppBigBanner()));
//     }
        unionApp.setAppId(CommonFunctionHelper.getUid());//DISTRIBUTED_ID
        unionApp.setAppCode(CommonFunctionHelper.getUid());//AUTO_GENERATE
        unionApp.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        unionApp.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        unionApp.setIsArchive("FALSE");
        unionApp.setCreateInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        unionApp.setCreateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        unionApp.setIsValid("FALSE");
        unionApp.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
        unionApp.setAscriptionAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            unionApp.setReleaseInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//RELEASED_CURRENT_INDUCTIONID
        }
        if (unionApp != null && unionApp.getSubjectLifeCycle() != null && unionApp.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            unionApp.setReleaseTime(CommonFunctionHelper.getCurrentTime());//RELEASE_SYSTEM_CURRENT_TIME
        }
        if (super.save(unionApp)) {
            return unionApp.getAppId();
        } else {
            return "-1";
        }

    }

    /**
     * M1删除联盟应用测试[4876]
     * gen by moon at 10/23/2022, 2:25:44 PM
     */
    @Trace(operationName = "M1删除联盟应用测试")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAppTestData(String appId) {

        return super.removeById(appId);
    }

    /**
     * M1查询联盟应用测试详情[4877]
     * gen by moon at 10/23/2022, 2:25:45 PM
     */
    @Trace(operationName = "M1查询联盟应用测试详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UnionApp queryAppTestDataDetail(UnionApp unionApp) {

        try {

            QueryWrapper<UnionApp> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(unionApp);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<UnionApp> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                UnionApp retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-2-06查询联盟应用（空间ID推内存）详情[9642]
     * gen by moon at 6/9/2024, 4:01:33 PM
     */
    @Trace(operationName = "1-2-06查询联盟应用（空间ID推内存）详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UnionApp queryAppForPushMemoryDetail(QueryAppForPushMemoryDetailReq reqDto) {

        try {
            reqDto.setIsValid("FALSE");
            QueryWrapper<UnionApp> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<UnionApp> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                UnionApp retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

}
